package com.ev.k3cloudBusiness.service.impl;

import com.ev.asl.constant.AslConstant;
import com.ev.framework.utils.R;
import com.ev.framework.utils.ShiroUtils;
import com.ev.k3cloud.service.kingdeeMiddlewareService;
import com.ev.k3cloudBusiness.service.K3SEOutStockSynService;
import com.ev.k3cloudBusiness.vo.*;
import com.ev.mes.dao.SeOutStockDao;
import com.ev.mes.domain.SeOutStockDO;
import com.ev.mes.domain.SeOutStockDetailDO;
import com.google.common.collect.Lists;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 发货通知单
 * @author 姚家乐
 * @since 2021/7/19 15:37
 */
@Slf4j
@Service
public class K3SEOutStockSynServiceImpl implements K3SEOutStockSynService {

    @Autowired
    private kingdeeMiddlewareService kingdeeMiddlewareService;

    @Autowired
    private SeOutStockDao            seoutStockDao;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public R seOutStockSyn() {
        String seOutStockResult = kingdeeMiddlewareService.seOutStockAll();
        K3DeeSyncVO<List<K3SEOutStockResult>> kingdeeSyncVO = new Gson().fromJson(seOutStockResult,new TypeToken<K3DeeSyncVO<List<K3SEOutStockResult>>>(){}.getType());
        if(!AslConstant.ZERO.equals(kingdeeSyncVO.getCode())) {
            log.info(kingdeeSyncVO.getMsg());
            return  R.error(kingdeeSyncVO.getMsg());
        }
        List<K3SEOutStockResult> k3SEOutStockResults = kingdeeSyncVO.getData();
        if (k3SEOutStockResults.size() > 0) {
            List<SeOutStockDO> seOutStockDOList = seoutStockDao.selectAll();

            // 本地
            List<Long> localIdList = seOutStockDOList.stream().map(SeOutStockDO::getId).collect(Collectors.toList());
            // K3Cloud
            List<Long> remoteIdList = k3SEOutStockResults.stream().map(K3SEOutStockResult::getFInterID)
                    .collect(Collectors.toList());
            // 删除的 k3无，本地有
            List<Long> deleteIdList = localIdList.stream().filter(e -> !remoteIdList.contains(e))
                    .collect(Collectors.toList());
            // 修改的（本地库有的，远端库有的）
            List<Long> updateIdList = remoteIdList.stream().filter(localIdList::contains)
                    .collect(Collectors.toList());
            // 新增的（本地库无的，远端库有的）
            remoteIdList.removeAll(updateIdList);
            if (deleteIdList.size() > 0) {
                seoutStockDao.batchRemove(deleteIdList.toArray(new Long[0]));
                seoutStockDao.batchRemoveDetail(deleteIdList.toArray(new Long[0]));
                log.info("批量删除");
            }
            Long userId = ShiroUtils.getUserId();
            Date date = new Date();
            if(updateIdList.size() > 0){
                List<K3SEOutStockResult> resultList = k3SEOutStockResults.stream().filter(e->updateIdList.contains(e.getFInterID())).collect(Collectors.toList());
                List<SeOutStockDO> seOutStockDOS = seOutStockDOList.stream().filter(e->updateIdList.contains(e.getId())).collect(Collectors.toList());
                K3SEOutStockResult result ;
                for (SeOutStockDO seOutStockDO : seOutStockDOS) {
                    result = resultList.stream().filter(e->seOutStockDO.getId().equals(e.getFInterID())).collect(Collectors.toList()).get(0);
                    seOutStockDO.setFBillNo(result.getFBillNo());
                    seOutStockDO.setFDate(result.getFDate());
                    seOutStockDO.setFCuStID(result.getFCuStID());
                    seOutStockDO.setKeHu(result.getKeHu());
                    seOutStockDO.setUpdateBy(userId);
                    seOutStockDO.setUpdateTime(date);
                }
                seoutStockDao.batchUpdate(seOutStockDOS);
                seoutStockDao.batchRemoveDetail(updateIdList.toArray(new Long[0]));
                List<SeOutStockDetailDO> detailDOList = Lists.newArrayList();
                for (K3SEOutStockResult vo : resultList) {
                    List<K3SEOutStockDetailResult> detailResults = vo.getDetailVos();
                    for (K3SEOutStockDetailResult detailResult : detailResults) {
                        SeOutStockDetailDO detailDO = new SeOutStockDetailDO();
                        detailDO.setMainId(vo.getFInterID());
                        detailDO.setFEntryID(detailResult.getFEntryID());
                        detailDO.setFItemID(detailResult.getFItemID());
                        detailDO.setFNumber(detailResult.getFNumber());
                        detailDO.setFName(detailResult.getFName());
                        detailDO.setFModel(detailResult.getFModel());
                        detailDO.setFUnit(detailResult.getFUnit());
                        detailDO.setFQty(detailResult.getFQty());

                        detailDO.setCreateBy(userId);
                        detailDO.setCreateTime(date);
                        detailDO.setUpdateBy(userId);
                        detailDO.setUpdateTime(date);
                        detailDO.setDelFlag(0);
                        detailDOList.add(detailDO);
                    }
                }
                seoutStockDao.batchSaveDetail(detailDOList);
            }
            if (remoteIdList.size() > 0) {
                List<K3SEOutStockResult> resultList = k3SEOutStockResults.stream()
                        .filter(e -> remoteIdList.contains(e.getFInterID())).collect(Collectors.toList());
                List<SeOutStockDO> list = Lists.newArrayList();
                List<SeOutStockDetailDO> detailDOList = Lists.newArrayList();
                for (K3SEOutStockResult result : resultList) {
                    SeOutStockDO seOutStockDO = new SeOutStockDO();
                    seOutStockDO.setId(result.getFInterID());
                    seOutStockDO.setFBillNo(result.getFBillNo());
                    seOutStockDO.setFDate(result.getFDate());
                    seOutStockDO.setFCuStID(result.getFCuStID());
                    seOutStockDO.setKeHu(result.getKeHu());
                    seOutStockDO.setCreateBy(userId);
                    seOutStockDO.setCreateTime(date);
                    seOutStockDO.setUpdateBy(userId);
                    seOutStockDO.setUpdateTime(date);
                    seOutStockDO.setDelFlag(0);

                    list.add(seOutStockDO);

                    List<K3SEOutStockDetailResult> detailVos = result.getDetailVos();
                    for (K3SEOutStockDetailResult detailVo : detailVos) {
                        SeOutStockDetailDO detailDO = new SeOutStockDetailDO();
                        detailDO.setMainId(result.getFInterID());
                        detailDO.setFEntryID(detailVo.getFEntryID());
                        detailDO.setFItemID(detailVo.getFItemID());
                        detailDO.setFNumber(detailVo.getFNumber());
                        detailDO.setFName(detailVo.getFName());
                        detailDO.setFModel(detailVo.getFModel());
                        detailDO.setFUnit(detailVo.getFUnit());
                        detailDO.setFQty(detailVo.getFQty());

                        detailDO.setCreateBy(userId);
                        detailDO.setCreateTime(date);
                        detailDO.setUpdateBy(userId);
                        detailDO.setUpdateTime(date);
                        detailDO.setDelFlag(0);
                        detailDOList.add(detailDO);
                    }
                }

                if (!CollectionUtils.isEmpty(list)){
                    seoutStockDao.batchSave(list);
                    seoutStockDao.batchSaveDetail(detailDOList);
                    log.info("批量新增");
                }
            }
        }
        return R.ok();
    }
}
